package com.neusoft.grid.controller;

import com.neusoft.grid.entity.Mission;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.io.*;
import java.net.URL;
import java.util.Map;
import java.util.ResourceBundle;

public class GridMissionViewController implements Initializable {

    @FXML private Text SumMission;
    @FXML private Text WaitingMission;
    @FXML private Text DoneMission;
    @FXML private TableColumn<Mission, String> reporterColumn;
    @FXML private TableColumn<Mission, String> phoneColumn;
    @FXML private TableColumn<Mission, String> gridColumn;
    @FXML private TableColumn<Mission, String> locationColumn;
    @FXML private TableColumn<Mission, String> levelColumn;
    @FXML private TableColumn<Mission, String> descriptionColumn;
    @FXML private TableColumn<Mission, Void> actionColumn;

    @FXML private TableView<Mission> table;

    private final ObservableList<Mission> missionData = FXCollections.observableArrayList();

    private Map<String,Mission> missionMap = null;
    private static String totalMissionCount;
    private String sumMission = null;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        setupTableColumns();
        try {
            loadMissionsFromFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (totalMissionCount == null) {
            totalMissionCount = String.valueOf(missionMap.size());
        }

        sumMission = totalMissionCount;
        addActionButtonToTable();
        updateMissionCounters();
    }

    private void setupTableColumns() {
        reporterColumn.setCellValueFactory(new PropertyValueFactory<>("reporter"));
        phoneColumn.setCellValueFactory(new PropertyValueFactory<>("phone"));
        gridColumn.setCellValueFactory(new PropertyValueFactory<>("grid"));
        locationColumn.setCellValueFactory(new PropertyValueFactory<>("location"));
        levelColumn.setCellValueFactory(new PropertyValueFactory<>("level"));
        descriptionColumn.setCellValueFactory(new PropertyValueFactory<>("description"));
    }

    public void refreshMissionList() {
        missionData.clear();
        try {
            loadMissionsFromFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        updateMissionCounters();
    }

    private void updateMissionCounters() {
        SumMission.setText(sumMission);
        WaitingMission.setText(String.valueOf(missionMap.size()));
        // 已处理数 = 总数 - 待处理数
        DoneMission.setText(String.valueOf(Integer.parseInt(sumMission) - missionMap.size()));
    }

    private void loadMissionsFromFile() throws IOException {
        File file = new File("src/com/neusoft/grid/data/mission.txt");

        if (!file.exists()) {
            System.err.println("任务文件 mission.txt 不存在");
            return;
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            try {
                missionMap = (Map<String, Mission>) ois.readObject();
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
            for (Map.Entry<String,Mission> mission : missionMap.entrySet()){
                missionData.add(mission.getValue());
            }
            table.setItems(missionData);
        } catch (IOException e) {
            System.err.println("读取任务文件失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void addActionButtonToTable() {
        actionColumn.setCellFactory(param -> new TableCell<>() {
            private final Button btn = new Button("处理任务");

            {
                btn.setOnAction(event -> {
                    Mission mission = getTableView().getItems().get(getIndex());
                    try {
                        openMissionSubmitView(mission);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                setGraphic(empty ? null : btn);
            }
        });
    }

    private void openMissionSubmitView(Mission mission) throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/com/neusoft/grid/view/MissionSubmitView.fxml"));
        Parent root = loader.load();

        MissionSubmitViewController controller = loader.getController();
        controller.initData(mission, this); // 传递当前控制器引用

        SumMission.setText(sumMission);
        WaitingMission.setText(String.valueOf(missionMap.size()));
        DoneMission.setText(String.valueOf(Integer.valueOf(sumMission)-missionMap.size()));

        File file = new File("src/com/neusoft/grid/data/nowMission.txt");
        try {
            if (!file.exists() || file.length() == 0) {
                System.out.println("Data file missing or empty");
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            String nowMission = mission.getNumber();
            oos.writeObject(nowMission);
            oos.close();
        } catch (IOException e) {
            System.err.println("Error loading data or FXML");
            e.printStackTrace();
        }
        Stage stage = new Stage();
        stage.setScene(new Scene(root));
        stage.setTitle("任务处理");
        stage.show();
    }
}